package com.willpower.eureka.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willpower.eureka.mapper.UserMapper;
import com.willpower.eureka.pojo.User;
import com.willpower.eureka.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * @author: wen-yi;
 * @date: 2021/10/31 12:45;
 * @Description:
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //模拟： 根据用户名查询数据库
        log.info("执行登录: {}", username);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        // wrapper.select(user -> !user.getColumn().equals("password")) //必须查询出数据库密码做比对
        wrapper.eq(User::getUsername,username);
        User user = StrUtil.isEmpty(username)?null:getOne(wrapper);
        //User user = getOne(new QueryWrapper<User>().eq("username", username));
        log.info("user: {}", user);
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //根据查询对象进行获取密码权限
        //String password = passwordEncoder.encode("990716");
        String password = user.getPassword();
        // log.info("password:{}", password);
        List<GrantedAuthority> GrantedAuthority;
        if ("admin".equals(username)) GrantedAuthority= AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin");
        else GrantedAuthority= AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user");
        // 用户名、密码、权限列表
        return new User(username,password,user.isAccountNonExpired(),user.isAccountNonLocked(),user.isCredentialsNonExpired(),
                user.isEnabled(), GrantedAuthority);
    }
}
